package com.hyd.tweet.util;

import com.google.appengine.api.xmpp.JID;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * (description)
 *
 * @author yiding.he
 */
public class StringUtils {

    public static boolean isEmpty(String s) {
        return s == null || s.trim().equals("");
    }

    public static String combine(List<String> list, int startIndex) {
        StringBuilder sb = new StringBuilder();
        for (int i = startIndex, size = list.size(); i < size; i++) {
            sb.append(list.get(i)).append(" ");
        }
        return sb.toString().trim();
    }

    public static String getAccontFromJID(JID jid) {
        String id = jid.getId();
        return id.contains("/") ? id.substring(0, id.indexOf("/")) : id;
    }

    public static void removeEmptyElements(ArrayList<String> list) {
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            if (isEmpty(next)) {
                iterator.remove();
            }
        }
    }

    public static String now(twitter4j.User twitterUser, String pattern) {
        int offset = twitterUser.getUtcOffset();
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.SECOND, offset);
        return new SimpleDateFormat(pattern).format(c.getTime());
    }

    public static String removeEnd(String str, String end) {
        if (isEmpty(str) || isEmpty(end)) {
            return str;
        }

        if (str.length() < end.length()) {
            return str;
        }
        
        return str.endsWith(end)? str.substring(0, str.length() - end.length()): str;
    }

    public static String[] splitTweet(String string) {
        int fragSize = 135;
        int fragCount = (string.length() + fragSize - 1) / fragSize;
        String[] result = new String[fragCount];

        for (int i = 1; i <= fragCount; i++) {
            String header = "(" + i + "/" + fragCount + ")";
            String body = string.substring((i - 1) * fragSize, Math.min(string.length(), i * fragSize));
            result[i - 1] = header + body;
        }

        return result;
    }
}
